<template>
  <div class="gantt-page">
    <div class="filter-container">
      <div class="left-filters">
        <el-select v-model="selectedProject" placeholder="选择项目" class="filter-select">
          <el-option
            v-for="item in projects"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="selectedStatus" placeholder="任务状态" class="filter-select">
        <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="right-filters">
        <el-button-group class="time-buttons">
          <el-button :class="{ active: timeRange === 'today' }" @click="setTimeRange('today')">今天</el-button>
          <el-button :class="{ active: timeRange === 'week' }" @click="setTimeRange('week')">本周</el-button>
          <el-button :class="{ active: timeRange === 'month' }" @click="setTimeRange('month')">本月</el-button>
          <el-button :class="{ active: timeRange === 'all' }" @click="setTimeRange('all')">全部</el-button>
        </el-button-group>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
          class="date-picker"
        />
        <el-button type="primary" @click="applyFilters">应用</el-button>
      </div>
    </div>

    <div ref="gantt" class="gantt-container"></div>
    
    <div class="legend-container">
      <div class="legend-title">状态说明：</div>
      <div class="legend-items">
        <div class="legend-item">
          <div class="color-box" style="background-color: #84bd54;"></div>
          <span>已完成</span>
        </div>
        <div class="legend-item">
          <div class="color-box" style="background-color: #fcca02;"></div>
          <span>进行中</span>
      </div>
        <div class="legend-item">
          <div class="color-box" style="background-color: #da645d;"></div>
          <span>延期/风险</span>
          </div>
        <div class="legend-item">
          <div class="color-box" style="background-color: #d1a6ff;"></div>
          <span>未开始</span>
        </div>
      </div>
    </div>

    <!-- 添加历史记录对话框 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="任务更新历史"
      width="600px"
      destroy-on-close
    >
      <div class="task-info" v-if="currentTask">
        <h3>{{ currentTask.text }}</h3>
        <div class="task-basic-info">
          <span>开始日期: {{ currentTask.start_date }}</span>
          <span>时长: {{ currentTask.duration }}天</span>
          <span>当前进度: {{ Math.round(currentTask.progress * 100) }}%</span>
      </div>
      </div>
      
      <el-timeline v-if="currentTask && currentTask.history">
        <el-timeline-item
          v-for="(activity, index) in currentTask.history"
          :key="index"
          :timestamp="activity.timestamp"
          :type="getTimelineItemType(activity.type)"
          :color="getTimelineItemColor(activity.type)"
        >
          {{ activity.content }}
          <div class="history-detail" v-if="activity.detail">
            <span v-if="activity.detail.from !== undefined">
              从 <span class="value-changed">{{ formatHistoryValue(activity.detail.from) }}</span> 
              更新到 <span class="value-changed">{{ formatHistoryValue(activity.detail.to) }}</span>
            </span>
            <span v-else>{{ activity.detail }}</span>
      </div>
          <div class="history-operator" v-if="activity.operator">
            操作人: {{ activity.operator }}
    </div>
        </el-timeline-item>
      </el-timeline>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="historyDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { gantt } from "dhtmlx-gantt";
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";

export default {
  name: "Gantt",
  data() {
    return {
      selectedProject: "1",
      selectedStatus: "all",
      timeRange: "month",
      dateRange: null,
      tasks: {
        data: []
      },
      projects: [
        { value: "1", label: "变电站电气安装工程" },
        { value: "2", label: "配电室改造项目" },
        { value: "3", label: "生产线电气升级" }
      ],
      statusOptions: [
        { value: "all", label: "全部" },
        { value: "completed", label: "已完成" },
        { value: "in-progress", label: "进行中" },
        { value: "pending", label: "待处理" },
        { value: "delayed", label: "已延期" }
      ],
      historyDialogVisible: false,
      currentTask: null
    };
  },
  methods: {
    setTimeRange(range) {
      this.timeRange = range;
      // 计算日期范围
      const today = new Date();
      let start, end;
      
      switch(range) {
        case 'today':
          start = new Date(today);
          end = new Date(today);
          break;
        case 'week':
          // 计算本周的开始和结束
          const dayOfWeek = today.getDay() || 7; // 如果是周日，getDay()返回0，我们转换为7
          start = new Date(today);
          start.setDate(today.getDate() - dayOfWeek + 1); // 设为周一
          end = new Date(start);
          end.setDate(start.getDate() + 6); // 设为周日
          break;
        case 'month':
          // 计算本月的开始和结束
          start = new Date(today.getFullYear(), today.getMonth(), 1);
          end = new Date(today.getFullYear(), today.getMonth() + 1, 0);
          break;
        case 'all':
        default:
          // 不设置日期范围
          this.dateRange = null;
          return;
      }
      
      // 格式化为YYYY-MM-DD
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };
      
      this.dateRange = [formatDate(start), formatDate(end)];
    },
    handleDateRangeChange(val) {
      if (val) {
        this.timeRange = 'custom';
      }
    },
    applyFilters() {
      this.initData();
      gantt.refreshData();
      
      if (this.dateRange && this.dateRange[0] && this.dateRange[1]) {
        // 设置甘特图的日期范围
        gantt.config.start_date = new Date(this.dateRange[0]);
        gantt.config.end_date = new Date(this.dateRange[1]);
        gantt.render();
      }
    },
    getTaskColor(status, progress) {
      if (status === 'completed' || progress === 1) {
        return '#84bd54'; // 绿色 - 已完成
      } else if (status === 'delayed' || progress < 0.3) {
        return '#da645d'; // 红色 - 延期/风险
      } else if (status === 'in-progress' || progress > 0) {
        return '#fcca02'; // 黄色 - 进行中
      } else {
        return '#d1a6ff'; // 紫色 - 未开始
      }
    },
    getTaskStatus(statusCode) {
      switch(statusCode) {
        case 'green': 
          return 'completed';
        case 'yellow': 
          return 'in-progress';
        case 'red': 
          return 'delayed';
        case 'pink':
        case 'popular':
          return 'pending';
        default:
          return 'in-progress';
      }
    },
    initData() {
      // 根据筛选条件过滤任务
      const filteredTasks = [
        // 技术研发阶段任务
  {
    id: 1,
          text: "技术研发 - 整体",
          start_date: "2025-04-01",
          duration: 30,
          progress: 0.8,
          status: "yellow",
          isMain: true
        },
        // 需求分析
        {
          id: 11,
          text: "需求分析",
          start_date: "2025-04-01",
          duration: 10,
          progress: 1,
          status: "green"
        },
        // 概念设计
        {
          id: 12,
          text: "概念设计",
          start_date: "2025-04-11",
          duration: 10,
          progress: 0.8,
          status: "yellow"
        },
        // 详细设计
        {
          id: 13,
          text: "详细设计",
          start_date: "2025-04-21",
          duration: 10,
          progress: 0.6,
          status: "yellow"
        },
        
        // 设备制造阶段任务
  {
    id: 2,
          text: "设备制造 - 整体",
          start_date: "2025-06-01",
          duration: 25,
          progress: 0.6,
          status: "yellow",
          isMain: true
        },
        // 零部件生产
        {
          id: 21,
          text: "零部件生产",
          start_date: "2025-06-01",
          duration: 15,
          progress: 0.8,
          status: "yellow"
        },
        // 设备组装
        {
          id: 22,
          text: "设备组装",
          start_date: "2025-06-16",
          duration: 10,
          progress: 0.3,
          status: "pink"
        },
        
        // 设备采购阶段任务
  {
    id: 3,
          text: "设备采购 - 整体",
          start_date: "2025-06-15",
          duration: 20,
          progress: 0.4,
          status: "yellow",
          isMain: true
        },
        // 供应商选择
        {
          id: 31,
          text: "供应商选择",
          start_date: "2023-06-15",
          duration: 8,
          progress: 0.9,
          status: "green"
        },
        // 合同签署
        {
          id: 32,
          text: "合同签署",
          start_date: "2025-06-23",
          duration: 4,
          progress: 0.5,
          status: "yellow"
        },
        // 设备运输
        {
          id: 33,
          text: "设备运输",
          start_date: "2025-06-27",
          duration: 8,
          progress: 0,
          status: "pink"
        },
        
        // 现场安装阶段任务
        {
          id: 4,
          text: "现场安装 - 整体",
          start_date: "2025-07-05",
          duration: 20,
          progress: 0,
          status: "popular",
          isMain: true
        },
        // 现场准备
        {
          id: 41,
          text: "现场准备",
          start_date: "2025-07-05",
          duration: 5,
          progress: 0,
          status: "popular"
        },
        // 设备安装
        {
          id: 42,
          text: "设备安装",
          start_date: "2025-07-10",
          duration: 15,
          progress: 0,
          status: "popular"
        },
        
        // 调试阶段任务
        {
          id: 5,
          text: "调试 - 整体",
          start_date: "2025-07-25",
          duration: 15,
          progress: 0,
          status: "popular",
          isMain: true
        },
        // 单机调试
        {
          id: 51,
          text: "单机调试",
          start_date: "2025-07-25",
          duration: 7,
          progress: 0,
          status: "popular"
        },
        // 系统联调
        {
          id: 52,
          text: "系统联调",
          start_date: "2025-08-01",
          duration: 8,
          progress: 0,
          status: "popular"
        },
        
        // 验收阶段任务
        {
          id: 6,
          text: "验收 - 整体",
          start_date: "2025-08-09",
          duration: 10,
          progress: 0,
          status: "popular",
          isMain: true
        },
        // 性能测试
        {
          id: 61,
          text: "性能测试",
          start_date: "2025-08-09",
          duration: 5,
          progress: 0,
          status: "popular"
        },
        // 最终验收
        {
          id: 62,
          text: "最终验收",
          start_date: "2025-08-14",
          duration: 5,
          progress: 0,
          status: "popular"
        }
      ];

      // 根据选择的状态进行筛选
      if (this.selectedStatus !== 'all') {
        this.tasks.data = filteredTasks
          .filter(task => this.getTaskStatus(task.status) === this.selectedStatus)
          .map(task => {
            const taskStatus = this.getTaskStatus(task.status);
            
            // 模拟历史记录数据
            const historyData = this.generateTaskHistory(task);
            
            return {
              ...task,
              toolTipsTxt: `${task.text}（${taskStatus === 'completed' ? '已完成' : 
                                          taskStatus === 'in-progress' ? '进行中' : 
                                          taskStatus === 'delayed' ? '已延期' : '待处理'}）`,
              color: this.getTaskColor(taskStatus, task.progress),
              history: historyData  // 添加历史记录
            };
          });
      } else {
        // 不筛选状态
        this.tasks.data = filteredTasks.map(task => {
          const taskStatus = this.getTaskStatus(task.status);
          
          // 模拟历史记录数据
          const historyData = this.generateTaskHistory(task);
          
          return {
            ...task,
            toolTipsTxt: `${task.text}（${taskStatus === 'completed' ? '已完成' : 
                                        taskStatus === 'in-progress' ? '进行中' : 
                                        taskStatus === 'delayed' ? '已延期' : '待处理'}）`,
            color: this.getTaskColor(taskStatus, task.progress),
            history: historyData  // 添加历史记录
          };
        });
      }
    },
    generateTaskHistory(task) {
      // 根据任务ID生成模拟的历史记录
      // 在实际应用中，这些数据应该从后端API获取
      const histories = [];
      
      // 创建任务记录
      histories.push({
        type: "create",
        timestamp: this.getRandomPastDate(90),
        content: "创建了任务",
        operator: "张工",
        detail: task.text
      });
      
      // 若任务进度大于0，添加进度更新记录
      if (task.progress > 0) {
        const progressSteps = Math.floor(task.progress * 10);
        for (let i = 1; i <= progressSteps; i++) {
          const progress = i * 10;
          histories.push({
            type: "update",
            timestamp: this.getRandomPastDate(90 - i * 8),
            content: "更新了任务进度",
            operator: this.getRandomOperator(),
            detail: {
              from: `${progress - 10}%`,
              to: `${progress}%`
            }
          });
        }
      }
      
      // 若为主任务，添加一些阶段性记录
      if (task.isMain) {
        histories.push({
          type: "milestone",
          timestamp: this.getRandomPastDate(60),
          content: "任务阶段审核通过",
          operator: "项目经理"
        });
      }
      
      // 若任务状态为已完成，添加完成记录
      if (task.status === "green" || task.progress === 1) {
        histories.push({
          type: "complete",
          timestamp: this.getRandomPastDate(10),
          content: "任务已完成",
          operator: this.getRandomOperator()
        });
      }
      
      // 若任务有风险，添加风险记录
      if (task.status === "pink" || task.status === "red") {
        histories.push({
          type: "warning",
          timestamp: this.getRandomPastDate(20),
          content: "任务存在风险",
          operator: this.getRandomOperator(),
          detail: "可能延期完成，需要协调资源"
        });
      }
      
      // 按时间排序
      return histories.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    },
    
    getRandomPastDate(maxDaysAgo) {
      const today = new Date();
      const daysAgo = Math.floor(Math.random() * maxDaysAgo);
      const date = new Date(today);
      date.setDate(today.getDate() - daysAgo);
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    getRandomOperator() {
      const operators = ["张工", "李工", "王工", "赵工"];
      return operators[Math.floor(Math.random() * operators.length)];
    },
    
    showTaskHistory(taskId) {
      const task = this.tasks.data.find(t => t.id.toString() === taskId.toString());
      if (task) {
        this.currentTask = task;
        this.historyDialogVisible = true;
      }
    },
    
    getTimelineItemType(type) {
      const types = {
        "create": "primary",
        "update": "",
        "milestone": "success",
        "complete": "success",
        "warning": "warning"
      };
      return types[type] || "";
    },
    
    getTimelineItemColor(type) {
  const colors = {
        "create": "#409EFF",
        "update": "#909399",
        "milestone": "#67C23A",
        "complete": "#67C23A",
        "warning": "#E6A23C"
      };
      return colors[type] || "";
    },
    
    formatHistoryValue(value) {
      return value;
    }
  },
  mounted() {
    this.initData();

    // 设置甘特图配置
    gantt.config.autosize = true;
    gantt.config.readonly = true;
    gantt.config.show_grid = true;

    // 表格列设置
    gantt.config.columns = [
      {
        name: "text",
        label: "任务名称",
        tree: false,
        width: "250",
        resize: true,
        template: function(task) {
          // 确保任务名称显示
          return task.text;
        }
      },
      {
        name: "start_date",
        label: "开始日期",
        align: "center",
        width: "120",
        resize: true
      },
      {
        name: "duration",
        label: "时长",
        align: "center",
        width: "80",
        resize: true,
        template: function (obj) {
          return obj.duration + "天";
        }
      },
      {
        name: "progress",
        label: "进度",
        align: "center",
        width: "80",
        resize: true,
        template: function (obj) {
          return Math.round(obj.progress * 100) + "%";
        }
      },
      {
        name: "history",
        label: "操作",
        align: "center",
        width: "80",
        template: function(task) {
          return "<div class='gantt-history-btn' data-task-id='" + task.id + "'>历史</div>";
        }
      }
    ];

    // 时间轴格式设置
    var weekScaleTemplate = function (date) {
      var weekNum = gantt.date.date_to_str("第 %W 周");
      return weekNum(date);
    };
    
    var daysStyle = function (date) {
      var dateToStr = gantt.date.date_to_str("%D");
      if (dateToStr(date) == "六" || dateToStr(date) == "日")
        return "weekend";
      return "";
    };
    
    gantt.config.subscales = [
      {
        unit: "week",
        step: 1,
        template: weekScaleTemplate
      },
      {
        unit: "day",
        step: 1,
        format: "%d",
        css: daysStyle
      }
    ];

    // 启用tooltip插件
    gantt.plugins({
      tooltip: true
    });
    
    gantt.attachEvent("onGanttReady", function () {
      gantt.templates.tooltip_text = function (start, end, task) {
        return (
          task.toolTipsTxt +
          "<br/>" +
          "开始时间：" + gantt.templates.tooltip_date_format(start) +
          "<br/>" +
          "结束时间：" + gantt.templates.tooltip_date_format(end) +
          "<br/>" +
          "时长：" + task.duration + "天" +
          "<br/>" +
          "进度：" + Math.round(task.progress * 100) + "%"
        );
      };
    });

    // 设置任务条进度内容
    gantt.templates.progress_text = function (start, end, task) {
      return (
        "<div style='text-align:right;color:#fff;padding-right:10px'>" +
        Math.round(task.progress * 100) +
        "% </div>"
      );
    };

    // 任务条显示内容
    gantt.templates.task_text = function (start, end, task) {
      return (
        "<div style='text-align:left;color:#fff;padding-left:10px;width:80%'>" +
        task.text +
        " (" +
        task.duration +
        "天)" +
        "</div>"
      );
    };

    // 任务栏周末亮色
    gantt.templates.task_cell_class = function(item, date){
      if(date.getDay()== 0 || date.getDay()== 6){
        return "weekend";
      }
    };

    // 任务条样式
    gantt.templates.task_class = function (start, end, item) {
      return item.isMain ? "main-task" : "task-item";
    };

    // 布局设置
    gantt.config.layout = {
      css: "gantt_container",
      cols: [
        {
          width: 550,
          min_width: 300,
          rows: [
            {
              view: "grid",
              scrollX: "gridScroll",
              scrollable: true,
              scrollY: "scrollVer"
            },
            {
              view: "scrollbar",
              id: "gridScroll",
              group: "horizontal"
            }
          ]
        },
        {
          resizer: true,
          width: 1
        },
        {
          rows: [
            {
              view: "timeline",
              scrollX: "scrollHor",
              scrollY: "scrollVer"
            },
            {
              view: "scrollbar",
              id: "scrollHor",
              group: "horizontal"
            }
          ]
        },
        {
          view: "scrollbar",
          id: "scrollVer"
        }
      ]
    };

    // 设置任务相关尺寸
    gantt.config.task_height = 38;
    gantt.config.row_height = 48;
    gantt.config.show_task_cells = true;
    gantt.config.fit_tasks = true;
    gantt.config.min_column_width = 40;
    gantt.config.auto_types = true;
    gantt.config.xml_date = "%Y-%m-%d";
    gantt.config.scale_unit = "month";
    gantt.config.step = 1;
    gantt.config.date_scale = "%Y年%M";
    gantt.config.start_on_monday = true;
    gantt.config.scale_height = 90;
    gantt.config.autoscroll = true;
    
    // 设置初始时间范围 (默认显示本月)
    this.setTimeRange('month');
    if (this.dateRange && this.dateRange[0] && this.dateRange[1]) {
      gantt.config.start_date = new Date(this.dateRange[0]);
      gantt.config.end_date = new Date(this.dateRange[1]);
    }

    // 设置语言
    gantt.i18n.setLocale("cn");

    // 初始化甘特图
    gantt.init(this.$refs.gantt);
    gantt.parse(this.tasks);

    // 添加历史按钮点击事件
    gantt.event(gantt.$container, "click", (e) => {
      if(e.target.classList.contains('gantt-history-btn')) {
        const taskId = e.target.getAttribute('data-task-id');
        this.showTaskHistory(taskId);
      }
    });
  }
};
</script>

<style scoped>
.gantt-page {
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.left-filters {
  display: flex;
  align-items: center;
  gap: 15px;
}

.filter-select {
  width: 180px;
}

.right-filters {
  display: flex;
  align-items: center;
  gap: 15px;
}

.time-buttons {
  margin-right: 15px;
}

.date-picker {
  width: 280px;
}

.active {
  color: #409EFF;
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.gantt-container {
  flex: 1;
  height: calc(100vh - 180px);
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.legend-container {
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.legend-title {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 10px;
}

.legend-items {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.color-box {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  margin-right: 8px;
}

/* 添加历史记录按钮和对话框样式 */
.task-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.task-info h3 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 18px;
  color: #303133;
}

.task-basic-info {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  color: #606266;
  font-size: 14px;
}

.history-detail {
  font-size: 13px;
  color: #606266;
  margin-top: 5px;
}

.history-operator {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  text-align: right;
}

.value-changed {
  padding: 2px 5px;
  border-radius: 3px;
  background-color: #f0f9eb;
  color: #67c23a;
  font-weight: bold;
}
</style>

<style>
.task-item {
  border: none !important;
  border-radius: 4px;
}

.gantt_task_line {
  border-radius: 4px;
}

.gantt_task_content {
  font-size: 13px;
  font-weight: 500;
}

.weekend {
  background-color: #f4f7f4;
}

.gantt_grid_head_cell {
  font-weight: 500;
  color: #606266;
}

.gantt_grid_data .gantt_cell {
  border-right: 1px solid #e0e0e0;
}

.gantt_grid, .gantt_grid_data {
  border-left: 1px solid #e0e0e0;
}

.gantt_task_progress {
  background-color: rgba(0, 0, 0, 0.2);
}

.gantt_grid_scale .gantt_grid_head_cell,
.gantt_task .gantt_task_scale .gantt_scale_cell {
  border-right: 1px solid #e0e0e0;
}

.main-task {
  border: none !important;
  border-radius: 4px;
  background-color: #5692f0 !important;
}

.main-task .gantt_task_progress {
  background-color: rgba(255, 255, 255, 0.3);
}

.main-task .gantt_task_content {
  font-weight: bold;
}

/* 添加历史按钮样式 */
.gantt-history-btn {
  cursor: pointer;
  color: #409EFF;
  font-size: 12px;
  padding: 2px 6px;
  border: 1px solid #d9ecff;
  background-color: #ecf5ff;
  border-radius: 3px;
  display: inline-block;
}

.gantt-history-btn:hover {
  color: #fff;
  background-color: #409EFF;
  border-color: #409EFF;
}
</style> 
